package com.nblog.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.common.collect.Lists;
import com.jfinal.aop.Duang;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.nblog.cache.CacheClearUtils;
import com.nblog.cache.CacheName;
import com.nblog.constant.ApiConstant;
import com.nblog.model.SysRes;
import com.nblog.model.SysRole;
import com.nblog.model.SysUser;
import com.nblog.plugin.ioc.annotation.JFAutowired;
import com.nblog.plugin.ioc.annotation.JFService;
import com.nblog.resp.ApiResp;
import com.nblog.utils.CommonUtils;
import com.nblog.utils.encrypt.Md5Utils;
import com.nblog.view.InvokeResult;
@JFService
public class SysUserService {
	
	SysRoleService sysRoleService=Duang.duang(SysRoleService.class);
	public SysUser login(String username,String password){
		return SysUser.dao.findFirst("select * from sys_user where name=? and pwd=?", username,password);
	}
	/**
	 * 获取用户的所有资源
	 * @param uid
	 * @return
	 */
	public Set<String> getSysUserAllResUrl(int uid){
		System.out.println("getSysUserAllResUrl："+uid);
		Set<String> sets=CacheKit.get(CacheName.userMenuCache, "getSysUserAllResUrl_"+uid);
		if(sets==null){
			List<SysRes> list=getSysResList(uid,null);
			 sets=new HashSet<String>();
			for(SysRes item : list){
				sets.add(item.getStr("url"));
			}
			CacheKit.put(CacheName.userMenuCache, "getSysUserAllResUrl_"+uid, sets);
		}
		return sets;
	}
	/**
	 * 
	 * @param uid 用户ID
	 * @param type 菜单|功能
	 * @return
	 */
	public List<SysRes> getSysResList(int uid,Integer type){
		List<SysRes> resList=CacheKit.get(CacheName.userMenuCache, "getSysResList_"+uid+"_"+type);
		if(resList==null||resList.size()==0){
			List<SysRole> sysRoleIds=sysRoleService.getSysRoleIdList(uid);
			if(sysRoleIds.size()==0)return null;
			StringBuffer roleIds=new StringBuffer();
			boolean isAdmin=false;
			for(SysRole sysRole : sysRoleIds){
				if(sysRole.getId().equals(1))isAdmin=true;
				roleIds.append(sysRole.getInt("id")).append(",");
			}
				roleIds.deleteCharAt(roleIds.length()-1);
				if(type!=null){
					if(!isAdmin){
						resList= SysRes.dao.find("select * from sys_res where id in(select res_id from sys_role_res where role_id in("+roleIds.toString()+")) and type="+type+" and enabled=1  order by seq asc");
					}else{
						resList= SysRes.dao.find("select * from sys_res where type="+type+" and enabled=1 order by seq asc");
					}
				}else{
					if(!isAdmin){
						resList= SysRes.dao.find("select * from sys_res where id in(select res_id from sys_role_res where role_id in("+roleIds.toString()+")) and enabled=1 order by seq asc");
					}else{
						resList= SysRes.dao.find("select * from sys_res where enabled=1 order by seq asc");
					}
				}
			CacheKit.put(CacheName.userMenuCache, "getSysResList_"+uid+"_"+type, resList);
		}
		return resList;
	}
	/**
	 * 权限集
	 */
	public Set<String> getPermissionSets(int sysUserId) {
		return this.getSysUserAllResUrl(sysUserId);
	}
	/**
	 * 是否有管理员权限
	 */
	public boolean isAdmin(int id){
		long count=Db.queryLong("select count(*) from sys_user_role where role_id=? and user_id=?", 1,id);
		return  count>0?true:false;
	}
	/**
	 * 获取用户拥有的角色列表，最多查20个
	 * @author eason	
	 * @param uid
	 * @return
	 */
	public List<SysUser> getSysUserList(int uid){
		
		return SysUser.dao.paginate(1, 20, "select *", "from sys_user ",uid).getList();
	}
	
	public List<SysUser> getSysUserIdList(int uid){
		return SysUser.dao.paginate(1, 20, "select id", "from sys_user ",uid).getList();
	}
	
	public InvokeResult setVisible(String bids, Integer visible) {
		List<Integer> ids=CommonUtils.getIntegerListByStrs(bids);
		if(ids.contains(1)){
			return InvokeResult.failure("超级管理员不能被修改");
		}
		List<SysUser> modelList=new ArrayList<SysUser>();
		for(int id:ids){
			SysUser sysUser=new SysUser();
			sysUser.setId(id);
			sysUser.setStatus(visible);
			modelList.add(sysUser);
		}
		Db.batchUpdate(modelList, modelList.size());
		return InvokeResult.success("设置成功");
	} 
	/**
	 * 用户名是否已存在
	 * @param name
	 * @return
	 */
	public boolean hasExist(String name){
		long num=SysUser.dao.find("select count(*) as count from sys_user where name=?", name).get(0).getLong("count");
		return num>0?true:false;
	}
	public SysUser getByName(String name){
		return SysUser.dao.findFirst("select * from sys_user where name=?", name);
	}
	public InvokeResult save(Integer id,String username,String password,String des,String phone,String email){
		if(null!=id){
			SysUser sysUser=SysUser.dao.findById(id);
			if(password!=null&&!password.equals("")){
				sysUser.set("des", des).set("phone", phone).set("email", email).set("pwd", password).update();
			}else{
				sysUser.set("des", des).set("phone", phone).set("email", email).update();
			}
			
		}else {
			if(this.hasExist(username)){
				return InvokeResult.failure("用户名已存在");
			}else {
				if(StrKit.isBlank(password))password="123456";
				SysUser sysUser=new SysUser();
				sysUser.set("name", username).set("pwd", new Md5Utils().getMD5(password)).set("createdate", new Date()).set("des", des).set("phone", phone).set("email", email).save();
			}
		}
		return InvokeResult.success("添加成功");
	}
	/**
	 * 修改用户角色
	 * @param uid
	 * @param roleIds
	 * @return
	 */
	public InvokeResult changeUserRoles(Integer uid,String roleIds){
		Db.update("delete from sys_user_role where user_id = ?", uid);
		List<String> sqlList=Lists.newArrayList();
		for(String roleId : roleIds.split(",")){
			if(CommonUtils.isNotEmpty(roleId)){
				sqlList.add("insert into sys_user_role (user_id,role_id) values ("+uid+","+Integer.valueOf(roleId)+")");
			}
		}
		Db.batch(sqlList, sqlList.size());
		CacheClearUtils.clearUserMenuCache();
		return InvokeResult.success();
	};
	/**
	 * 密码修改
	 * @param uid
	 * @param newPwd
	 * @return
	 */
	public InvokeResult savePwdUpdate(Integer uid, String newPwd) {
		SysUser sysUser=SysUser.dao.findById(uid);
		if(sysUser!=null){
			sysUser.set("pwd", newPwd).update();
			return InvokeResult.success();
		}else{
			return InvokeResult.failure(-2, "修改失败");
		}
		
	}
	public Page<SysUser> getSysUserPage(int page, int rows, String keyword) {
		String select="select su.*, (select group_concat(name) as roleNames from sys_role where id in(select role_id from sys_user_role where user_id=su.id)) as roleNames";
		StringBuffer sqlExceptSelect=new StringBuffer("from sys_user su order by su.id desc");
		return SysUser.dao.paginate(page, rows, select, sqlExceptSelect.toString());
	}
	public ApiResp del(String idStrs){
		List<Integer> ids=CommonUtils.getIntegerListByStrs(idStrs);
		for(Integer id:ids){
			Db.delete("delete from sys_user_role where user_id=?", id);
			SysUser.dao.deleteById(id);
		}
		ApiResp resp=new ApiResp();
		resp.setCode(ApiConstant.CODE_SUCCESS);
		resp.setMsg("删除成功");
		return resp;
	}
}
